package com.example.qwen02.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ai")
@CrossOrigin
public class WanXiangContorller {
    @PostMapping("/upload")
    public Map<String, Object> updatePhoto(MultipartFile photo) throws IOException {
        if (photo == null) {
            System.out.println("上传失败，image为空！");
            return null;
        }
        photo.transferTo(new File("E:\\Vue\\photos\\" + photo.getOriginalFilename()));
        Map<String, Object> map = new HashMap<>();
        map.put("url", "https://public-vigen-video.oss-cn-shanghai.aliyuncs.com/public/dashscope/test.png");
        System.out.println("上传成功");
        System.out.println(map);
        return map;
    }

    /**
     * 使用HttpClient发送POST请求，生成对应风格的图片
     *
     * @param or_url
     * @param style
     * @return
     * @throws Exception
     */
    @PostMapping("/askStyleChange")
    public Map<String, Object> askStyleChange(String or_url, int style) throws Exception {
        System.out.println(or_url);

        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpPost对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation";
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        httpPost.setHeader("X-DashScope-Async", "enable");
        httpPost.setHeader("Authorization", "Bearer" + System.getenv("DASHSCOPE_API_KEY"));
        httpPost.setHeader("Content-type", "application/json");

        // JSON参数
        String jsonParam = "{\n" +
                "    \"model\": \"wanx-style-repaint-v1\",\n" +
                "    \"input\": {\n" +
                "        \"image_url\": \"" + or_url + "\",\n" +
                "        \"style_index\": " + style + "\n" +
                "    }\n" +
                "}";

        // 将JSON字符串转换为HttpEntity对象并设置到HttpPost中
        httpPost.setEntity(new StringEntity(jsonParam));

        try {
            // 执行HTTP POST请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 如果请求成功，读取响应实体
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            response.close();

            Map<String, Object> map = new HashMap<>();
            // result是json格式,我们提取出它的结果
            // 解析整个JSON字符串为一个JSONObject
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.containsKey("output")) {
                // 从JSONObject中获取名为"output"的子对象
                JSONObject outputObject = jsonObject.getJSONObject("output");
                // 从outputObject中提取task_id字段的值
                String taskId = outputObject.getString("task_id");
                map.put("state", "success");
                map.put("task_id", taskId);
            } else {
                map.put("state", "error");
                map.put("error", jsonObject.getString("message"));
            }
            System.out.println("post-Response: " + result);
            return map;
        } finally {
            httpClient.close();
        }
    }

    /**
     * 取图片
     * @param task_id
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/getImage",produces = "application/json;charset=utf-8")
    public String getImage(String task_id) throws IOException {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpPost对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/tasks/"+task_id;
//        HttpPost httpPost = new HttpPost(url);
        HttpGet httpGet = new HttpGet(url);

        // 设置请求头，包括Content-Type为application/json
        httpGet.setHeader("Authorization", "Bearer"+System.getenv("DASHSCOPE_API_KEY"));
        try {
            // 执行HTTP POST请求
            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("Response: " + result);
            response.close();
            return  result;

        } finally {
            httpClient.close();
        }
    }


    @RequestMapping("/txting")
    public Map<String, Object> txting(String txt,int qty) throws NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .model(ImageSynthesis.Models.WANX_V1)
                        .n(qty)
                        .size("1024*1024")
                        .prompt("txt")
                        .build();

        ImageSynthesisResult result = is.call(param);
        System.out.println(result);
        Map<String, Object> map = new HashMap<>();
        map.put("txt",txt);
        map.put("qty",qty);
        map.put("result",result.getOutput().getResults());
        return map;


    }

}
